package main

import (
	"encoding/json"
	"fmt"
	"log"

	"chatroom/server/internal/handlers"

	"chatroom/shared"

	amqp "github.com/rabbitmq/amqp091-go"
)

var handlerMap map[string]handlers.ICmdHandler

func main() {
	handlerMap = make(map[string]handlers.ICmdHandler)
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	ch, err := conn.Channel()
	if err != nil {
		panic(err)
	}
	defer ch.Close()

	queueName := "ChatRoom.Server"

	handlerMap["heartbeat"] = handlers.NewHandlerFactory("heartbeat", ch)
	handlerMap["chatmsg"] = handlers.NewHandlerFactory("chatmsg", ch)

	_, err = ch.QueueDeclare(
		queueName,
		false,
		true,
		false,
		false,
		nil,
	)

	if err != nil {
		panic(err)
	}

	msgs, err := ch.Consume(
		queueName,
		"",
		true,
		false,
		false,
		false,
		nil,
	)

	if err != nil {
		panic(err)
	}

	go func() {
		for msg := range msgs {
			var cmd shared.CommandMsg
			err := json.Unmarshal(msg.Body, &cmd)
			if err != nil {
				log.Printf("Error unmarshalling message: %v", err)
				continue
			}

			handler, ok := handlerMap[cmd.Command]
			if !ok {
				log.Printf("No handler found for command: %s", cmd.Command)
				continue
			}
			handler.Handle(cmd.Body)
		}
	}()
	fmt.Println("Successfully connect to RabbitMQ broker")
	fmt.Println("Prepare to receive messages from Client...")
	var input string
	fmt.Scanln(&input)
	if input == "exit" {
		return
	}
}
